<?php

class Application_Plugin_Acl extends Zend_Controller_Plugin_Abstract{
    
    private $_controller = array(
        'controller' => 'error',
        'action' => 'denied'
    );
    
    public function __construct() 
    {
        $acl = new Zend_Acl();
        
        //roles
        $acl->addRole(new Zend_Acl_Role('guest'));
        $acl->addRole(new Zend_Acl_Role('user'), 'guest');
        $acl->addRole(new Zend_Acl_Role('admin'));
        
        //resources
        $acl->add(new Zend_Acl_Resource('users'));
        $acl->add(new Zend_Acl_Resource('index'));
        $acl->add(new Zend_Acl_Resource('system:problems'));
        $acl->add(new Zend_Acl_Resource('system:status'));
        $acl->add(new Zend_Acl_Resource('system:tester'));
        
        
        //permissions
        $acl->deny();
        $acl->allow('admin', null);
        $acl->deny('admin', 'users', array(
            'registration'
        ));
        
        //Guest rights
        $acl->allow('guest', 'users', array(
            'login', 'registration'
        ));
        $acl->allow('guest', 'index', array(
            'index'
        ));
        
        //User rights
        $acl->allow('user', 'users', array(
            'logout', 'view'
        ));
        
        $acl->allow('user', 'system:problems', array(
            'index', 'view' 
        ));
        
        $acl->allow('user', 'system:tester', array(
            'index' 
        ));
        
        $acl->allow('user', 'system:status', array(
            'index', 'source'  
        ));
        
        $acl->deny('user', 'users', array(
            'registration' 
        ));
        
        Zend_Registry::set('acl', $acl);
    }


    public function preDispatch(Zend_Controller_Request_Abstract $request) {
        $auth = Zend_Auth::getInstance();
        $acl = Zend_Registry::get('acl');
        
        if($auth->hasIdentity())
        {
            $roles = new Application_Model_Roles();
            $role = $roles->getRole(Zend_Auth::getInstance()->getIdentity()->user_role_id);
        }
        else
        {
            $role = 'guest';
        }
        
        if (!$acl->hasRole($role))
        {
            $role = 'guest';
        }
        $modul = null;
        if ($request->module != "default")
        {
            $modul = $request->module . ':' ;
        }
        $controller = $modul . $request->controller;
        $action = $request->action;
        
        if (!$acl->has($controller))
        {
            $controller = null;
        }
        
        if (!$acl->isAllowed($role, $controller, $action))
        {
            $request->setControllerName($this->_controller['controller']);
            $request->setActionName($this->_controller['action']);
        }
    }
    
}

